package com.sky.service.admin.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sky.config.ThreadPoolConfiguration;
import com.sky.constant.MessageConstant;
import com.sky.dto.OrdersCancelDTO;
import com.sky.dto.OrdersConfirmDTO;
import com.sky.dto.OrdersPageQueryDTO;
import com.sky.dto.OrdersRejectionDTO;
import com.sky.exception.BaseException;
import com.sky.exception.OrderBusinessException;
import com.sky.mapper.admin.OrderDetailMapper;
import com.sky.mapper.admin.OrderMapper;
import com.sky.pojo.Courier;
import com.sky.pojo.OrderDetail;
import com.sky.pojo.Orders;
import com.sky.result.PageResult;
import com.sky.service.admin.OrderDispatchService;
import com.sky.service.admin.OrderService;
import com.sky.vo.OrderStatisticsVO;
import com.sky.vo.OrderVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;

@Service
@Slf4j
public class OrderServiceImpl implements OrderService {
    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private ThreadPoolConfiguration poolConfiguration;
    @Autowired
    private OrderDetailMapper orderDetailMapper;
    @Autowired
    private OrderDispatchService orderDispatchService;

    /**
     * 订单搜索
     * @param pageQueryDTO
     * @return
     */
    @Override
    public PageResult findByPage(OrdersPageQueryDTO pageQueryDTO) {
        PageHelper.startPage(pageQueryDTO.getPage(), pageQueryDTO.getPageSize());
        Page<OrderVO> pageBean = orderMapper.findBYPage(pageQueryDTO);
        return new PageResult(pageBean.getTotal(), pageBean.getResult());
    }

    /**
     * 统计订单数量
     * @return
     */
    @Override
    public OrderStatisticsVO countStatus() {
       /* ThreadPoolExecutor threadPool = poolConfiguration.threadPool();
        Future<Integer> waiting4MerchantReceiveOrdersFuture = threadPool.submit(()-> orderMapper.countStatus(Orders.TO_BE_CONFIRMED));
        Future<Integer> waitng4RiderReceiveOrdersFuture = threadPool.submit(()->orderMapper.countStatus(Orders.CONFIRMED));
        Future<Integer> toBeDeliveryOnProgressOrdersFuture = threadPool.submit(()-> orderMapper.countStatus(Orders.TOBEPICKEDUP));
        Future<Integer> toBeArrivedOrdersFuture = threadPool.submit(()-> orderMapper.countStatus(Orders.TOBEDELIVERED));
        Future<Integer> completedOrdersFuture = threadPool.submit(()-> orderMapper.countStatus(Orders.COMPLETE_ORDER));
        Future<Integer> canceledOrdersFuture = threadPool.submit(()-> orderMapper.countStatus(Orders.CANCELLED_ORDER));
        log.info("主线程继续执行{}",Thread.currentThread().getName());
        try {
            // 根据状态，   2 用户付款成功，等待商家接单  3.商家接单，等待骑手接单
            //     4 骑手接单成功-待取货  5待送达  6已完成  7已取消
            Integer waiting4MerchantReceiveOrders = waiting4MerchantReceiveOrdersFuture.get();
            Integer waitng4RiderReceiveOrders = waitng4RiderReceiveOrdersFuture.get();
            Integer toBeDeliveryOnProgressOrders = toBeDeliveryOnProgressOrdersFuture.get();
            Integer toBeArrivedOrders = toBeArrivedOrdersFuture.get();
            Integer completedOrders = completedOrdersFuture.get();
            Integer canceledOrders = canceledOrdersFuture.get();

            // 将查询出的数据封装到orderStatisticsVO中响应
            OrderStatisticsVO orderStatisticsVO = OrderStatisticsVO.builder()
                    .waiting4MerchantReceiveOrders(waiting4MerchantReceiveOrders)//  status = 2  等待商家接单
                    .waitng4RiderReceiveOrders(waitng4RiderReceiveOrders)//  status = 3  等待骑手接单
                    .toBeDeliveryOnProgressOrders(toBeDeliveryOnProgressOrders)//  status = 4  待出货订单数
                    .toBeArrivedOrders(toBeArrivedOrders)//  status = 5  待送达订单数
                    .completedOrders(completedOrders) // status = 6  已完成订单数
                    .canceledOrders(canceledOrders)//  status = 7  已取消订单数
                    .build();
            return orderStatisticsVO;
        } catch (Exception e) {
           log.info("获取线程结果异常",e);
        }
        return new OrderStatisticsVO();*/
        return orderMapper.countCaseStatus();
    }

    /**
     * 根据id查询订单全部信息
     * @param orderId
     * @return
     */
    @Override
    public OrderVO details(Long orderId) {
        Orders orders = orderMapper.findById(orderId);
        List<OrderDetail> orderDetails = orderDetailMapper.findByOrderId(orderId);
        //获取骑手电话
        Courier courier = orderMapper.findCourierByOrderNumber(orders.getNumber());
        OrderVO orderVO = new OrderVO();
        BeanUtils.copyProperties(orders, orderVO);
        orderVO.setOrderDetailList(orderDetails);
        orderVO.setCourierTelephone(courier == null ? null : courier.getTelephone());
        return orderVO;

    }

    /**
     * 管理端取消订单
     * @param dto
     */
    @Override
    public void cancelOrder(OrdersCancelDTO dto) {
        Orders orders = orderMapper.findById(dto.getId());
        if(orders==null || orders.getStatus()>4){
            throw new OrderBusinessException("-------订单状态不正确，无法取消-------");
        }
        orders.setCheckoutTime(LocalDateTime.now());
        orders.setStatus(Orders.CANCELLED_ORDER);
        orders.setCancelReason(dto.getCancelReason());
        orderMapper.updateOrder(orders);
    }

    /**
     * 拒绝接单
     * @param dto
     */
    @Override
    public void rejection(OrdersRejectionDTO dto) {
        Orders orders = orderMapper.findById(dto.getId());
        if(orders==null || !orders.getStatus().equals(Orders.TO_BE_CONFIRMED)){
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        }
        //若已经付款需要退款
        if(orders.getPayStatus()==(Orders.PAID)){
            log.info("需要退款");
        }
        orders.setRejectionReason(dto.getRejectionReason());
        orders.setStatus(Orders.CANCELLED_ORDER);
        orders.setCheckoutTime(LocalDateTime.now());
        orderMapper.updateOrder(orders);
    }

    /**
     * 商家接单
     * @param dto
     * @return
     */
    @Override
    public Courier confirm(OrdersConfirmDTO dto) {
        Orders orders = orderMapper.findById(dto.getId());
        if(orders==null){
            throw new OrderBusinessException(MessageConstant.ORDER_NOT_FOUND);
        }
        //查询骑手
        Courier courier = orderDispatchService.dispatch(orders);
        //修改订单状态为待接单
        if(courier == null){
            throw new BaseException("目前没有可用骑手，请稍后再试");
        }
        orders.setStatus(Orders.CONFIRMED);
        orderMapper.updateOrder(orders);
        return null;
    }
}
